import { useState, useRef, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { useSelector } from "react-redux";
import Title from "@/components/Title";

import styles from "./style.module.css";
import clsx from "clsx";
import ListItem from "./ListItem";

import request from "@/api/request";

import { useInput } from "@/hooks";
import { debounce, flushObject } from "@/tools";

const pageSize = 24;
const threshold = 2;
const MemberList = () => {
  const navigate = useNavigate();

  const [search, onSearchChange] = useInput() as any;
  const [realSearch, setRealSearch] = useState("");
  const [list, setList] = useState<any[]>([]);
  const positionRef = useRef({ total: 0, wrap: 0 });
  const listRef = useRef<any>(null);
  const listWrapRef = useRef<any>(null);
  const footerRef = useRef<any>(null);
  const canFetch = useRef(true);
  const mode = useRef("page");
  const [page, setPage] = useState(1);

  const filterInfo = useSelector((state: any) => (state.filter));

  const debounced = useCallback(debounce(setRealSearch), []);

  const handleSearchChange = (e) => {
    mode.current = "search";
    setPage(1);
    onSearchChange(e);
    debounced(e.target.value);
  };

  const handleScroll = (e) => {
    const { total, wrap } = positionRef.current;
    if (e.target.scrollTop + wrap + threshold >= total) {
      mode.current = "page";
      if (canFetch.current) {
        setPage(page + 1);
      }
      canFetch.current = false;
    }
  };

  useEffect(() => {
    request("/me-api/members", {
      method: "POST",
      params: {
        pageSize,
        page: page,
        search,
      },
      data: flushObject(filterInfo),
    }).then((res) => {
      // 异步批量操作
      if (mode.current === "page") {
        setList([...list, ...res.data]);
      }
      if (mode.current === "search") {
        setList(res.data);
      }

      setTimeout(() => {
        const total = listRef.current.offsetHeight;
        const wrapHeight = listWrapRef.current.offsetHeight;
        canFetch.current = true;
        positionRef.current = {
          total,
          wrap: wrapHeight,
        };
      }, 1);
    });
  }, [page, realSearch, filterInfo]);

  return (
    <div className="flex flex-col h-full">
      <Title
        extra={
          <div
            onClick={() => navigate("/pro-filter")}
            className={styles.filter}
          >
            筛选
          </div>
        }
      >
        我的会员
      </Title>
      <div className="px-[24px] py-[15px] relative bg-white">
        <i className={clsx("iconfont icon-search1", styles.searchIcon)}></i>
        <input
          type="text"
          value={search}
          placeholder="请输入会员昵称/手机号"
          className={clsx(styles.search, "w-full")}
          onChange={handleSearchChange}
        />
      </div>

      <div className="flex flex-1 flex-col overflow-hidden">
        <div
          className="h-full overflow-auto"
          ref={listWrapRef}
          onScroll={handleScroll}
        >
          <div className="list flex flex-col gap-x-[]" ref={listRef}>
            <div className={clsx(styles.listHead, "px-[24px]")}>
              会员列表（343人） 当前列表（{list.length}人）
            </div>
            {list.map((it: any) => (
              <ListItem data={it} key={it.id}></ListItem>
            ))}
            <div
              className="flex justify-center items-center text-center h-[80px]"
              ref={footerRef}
            >
              <div className={styles.customLoader}></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MemberList;
